<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="55%"
      :draggable="true"
      @close="closeDialog"
      class="family-detail-dialog"
    >
      <div class="dialog-header">
        <h2 class="family-name">{{ data.name }}</h2>
        <div class="family-meta">
        <span class="meta-item">
          <el-icon><User/></el-icon>
          创建者: {{ data.creatorName }}
        </span>
          <span class="meta-item">
          <el-icon><Clock/></el-icon>
          创建于: {{ formatDateTime(data.createAt) }}
        </span>
          <span class="meta-item">
          <el-icon><Location/></el-icon>
          地址: {{ data.address + ' ' + data.detailAddress }}
        </span>
        </div>
      </div>

      <!--家庭概览-->
      <el-tabs v-model="activeTab" type="card" class="detail-tabs">
        <el-tab-pane label="家庭概览" name="detail">
          <el-scrollbar height="400px">
            <div class="detail-content">
              <el-descriptions :column="2" border class="family-descriptions">
                <el-descriptions-item label="成员总数" label-class-name="desc-label">
                  <template #label>
                    <el-icon>
                      <User/>
                    </el-icon>
                    <span>成员总数</span>
                  </template>
                  <el-tag type="success" size="large">{{ members.length }}</el-tag>
                </el-descriptions-item>

                <el-descriptions-item label="标签总数" label-class-name="desc-label">
                  <template #label>
                    <el-icon>
                      <CollectionTag/>
                    </el-icon>
                    <span>标签总数</span>
                  </template>
                  <el-tag type="info" size="large">{{ tags.length }}</el-tag>
                </el-descriptions-item>

                <el-descriptions-item label="创建时间" label-class-name="desc-label">
                  <template #label>
                    <el-icon>
                      <Clock/>
                    </el-icon>
                    <span>创建时间</span>
                  </template>
                  {{ formatDateTime(data.createAt) }}
                </el-descriptions-item>
              </el-descriptions>

              <div class="quick-stats">
                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon color="#67C23A">
                      <User/>
                    </el-icon>
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ members.length }}</div>
                    <div class="stat-label">家庭成员</div>
                  </div>
                </div>

                <div class="stat-card">
                  <div class="stat-icon">
                    <el-icon color="#409EFF">
                      <CollectionTag/>
                    </el-icon>
                  </div>
                  <div class="stat-content">
                    <div class="stat-value">{{ tags.length }}</div>
                    <div class="stat-label">家庭标签</div>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </el-tab-pane>

        <el-tab-pane label="成员管理" name="members">
          <div class="member-management-header">
            <div class="header-left">
              <el-input
                v-model="memberSearchQuery"
                placeholder="搜索成员..."
                clearable
                style="width: 240px"
                class="search-input"
              >
                <template #prefix>
                  <el-icon>
                    <el-Search/>
                  </el-icon>
                </template>
              </el-input>

              <el-button
                type="info"
                plain
                @click="getMembersList(currentFamilyId)"
                class="refresh-btn"
              >
                <el-icon>
                  <el-Refresh/>
                </el-icon>
                <span>刷新</span>
              </el-button>
            </div>

            <div class="header-right">
              <el-button
                type="success"
                @click="handleAddMember"
                class="add-member-btn"
              >
                <el-icon>
                  <el-Plus/>
                </el-icon>
                <span>添加成员</span>
              </el-button>
            </div>
          </div>
          <el-scrollbar height="400px">
            <el-table
              :data="searchMembers"
              style="width: 100%"
              stripe
              class="member-table"
              :row-style="setRowStyle"
            >
              <el-table-column prop="name" label="成员姓名" width="180">
                <template #header>
                  <el-icon>
                    <User/>
                  </el-icon>
                  <span>成员姓名</span>
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色">
                <template #header>
                  <el-icon>
                    <Key/>
                  </el-icon>
                  <span>角色</span>
                </template>
                <template #default="{row}">
                  <el-tag :type="getRoleTagType(row.role)">
                    {{ getRoleName(row.role) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="170`">
                <template #default="{row}">
                  <div style="display: flex; gap: 8px;">
                    <el-button size="default"

                               color="#626aef"
                               @click="handleEditMember(row)">编辑
                    </el-button>
                    <el-button
                      type="danger"
                      @click="handleDeleteMember(row)"
                      v-if=" getRoleOrder(row.role) > currentRole.order"
                    >
                      删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </el-tab-pane>

        <el-tab-pane label="标签管理" name="tags">
          <el-scrollbar height="400px">
            <el-table
              :data="tags"
              style="width: 100%"
              stripe
              class="tag-table"
            >
              <el-table-column prop="name" label="标签名称">
                <template #header>
                  <el-icon>
                    <PriceTag/>
                  </el-icon>
                  <span>标签名称</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default>
                  <el-button size="default" color="#1F63FF">编辑</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!--编辑成员对话框-->
    <EditMemberDialog v-model:visible="editMemberVisible"
                      :data="editMemberData"
                      @refresh-member="getMembersList(currentFamilyId)"/>

    <!--添加成员对话框-->
    <AddMemberDialog v-model:visible="addMemberVisible"
                     :form-data="memberFormData"
                     :members="members"
                     @refresh-member="getMembersList(currentFamilyId)"
                     :current-family-id="currentFamilyId"/>
  </div>
</template>

<script setup lang="ts">
import {computed, ref, watch} from "vue";
import type {FamilyCard} from "@/api/family/type.ts";
import type {MemberForm, Member} from "@/api/member/type.ts";
import {
  User,
  Clock,
  CollectionTag,
  Key,
  PriceTag, Location
} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import AddMemberDialog from "@/views/family/detail/AddMemberDialog.vue";
import {useRoleStore} from "@/stores/useRoleStore.ts";
import {getTagListByFamilyId} from "@/api/tag";
import {deleteMemberById, getMembersById} from "@/api/member";
import type {TagCard} from "@/api/tag/type.ts";
import EditMemberDialog from "@/views/family/detail/EditMemberDialog.vue";
import type {RoleDictionary} from "@/api/role/type.ts";
import {getCurrentRole} from "@/api/role";

const activeTab = ref("detail");
const props = defineProps<{
  data: FamilyCard,
  visible: boolean,
}>();

const emit = defineEmits(["update:visible", 'refresh']);


// 对话框可见性
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit("update:visible", val)
});
//标签
const tags = ref<TagCard[]>([]);

/**
 * 获取标签列表
 * @param familyId
 */
async function getTagList(familyId: number) {
  try {
    const res = await getTagListByFamilyId(familyId)
    if (res.code === "M000") {
      tags.value = res.data;
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
    ElMessage.error("获取标签列表失败");
  }
}

//成员
const members = ref<Member[]>([]);

/**
 * 获取成员列表
 * @param familyId
 */
async function getMembersList(familyId: number) {
  try {
    const res = await getMembersById(familyId)
    if (res.code === "M000") {
      members.value = res.data;
    }
  } catch (error) {
    console.error("获取家庭成员列表失败:", error);
    ElMessage.error("获取家庭成员列表失败");
  }
}


//当前用户在此家庭中的角色
const currentRole = ref<RoleDictionary>({
  code: "",
  desc: "",
  order: -1
});

/**
 * 获取当前用户的角色
 * @param familyId
 */
async function getCurrentUserRole(familyId: number) {
  try {
    const res = await getCurrentRole(familyId!)
    if (res.code === "M000") {
      currentRole.value = res.data;
    }
  } catch (e) {
    console.error("获取当前用户角色失败", e)
    ElMessage.error("获取当前用户角色失败");
  }
}

//当前家庭id
const currentFamilyId = computed(() => props.data.id || 0);

/**
 * 监听当前家庭id变化
 */
watch(() => props.data.id, (newVal) => {
  getTagList(newVal!);
  getMembersList(newVal!)
  getCurrentUserRole(newVal!);
})

const setRowStyle = () => {
  return {
    height: '100px',
  };
};
//搜索成员
const memberSearchQuery = ref<string>('');

const searchMembers = computed(() => {
  return members.value.filter(f => f.name.startsWith(memberSearchQuery.value))
})


// 成员编辑相关状态
const editMemberVisible = ref(false);
const editMemberData = ref<Member>({
  id: null,
  name: '',
  role: '',
});

function handleEditMember(member: Member) {
  editMemberData.value = member;
  editMemberVisible.value = true;

}


const closeDialog = () => {
  dialogVisible.value = false;
};

const formatDateTime = (dateString: string) => {
  return new Date(dateString).toLocaleString();
};


//角色相关
const {getRoleName, getRoleOrder} = useRoleStore();

/**
 * 根据角色类型显示对应的标签type
 * @param role
 */
function getRoleTagType(role: string) {
  const roleTypes: Record<string, string> = {
    'OWNER': 'danger',
    'ADMIN': 'warning',
    'USER': 'success',
  };
  return roleTypes[role] || 'info';
}


function handleDeleteMember(member: Member) {
  ElMessageBox.confirm(
    `确定要删除成员 "${member.name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      customClass: 'modern-message-box'
    }
  ).then(async () => {
    try {
      const res = await deleteMemberById(currentFamilyId.value, member.id!);
      if (res.code === "M000") {
        //刷新成员列表
        await getMembersList(currentFamilyId.value);
        ElMessage.success('删除成功');
      }

    } catch (error) {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }).catch(() => {
    // 取消删除
  });
};


const addMemberVisible = ref(false)
const memberFormData = ref<MemberForm>({
    id: null,
    name: '',
    avatar: '',
    phone: '',
    username: ''
  })
;

function handleAddMember() {
  addMemberVisible.value = true
}


</script>

<style scoped lang="scss">
.family-detail-dialog {
  :deep(.el-dialog__header) {
    padding-bottom: 0;
    margin-right: 0;
  }

  :deep(.el-dialog__body) {
    padding-top: 10px;
  }

  .dialog-header {
    padding: 0 20px 15px;
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 15px;

    .family-name {
      margin: 0;
      font-size: 20px;
      color: #333;
      font-weight: 600;
    }

    .family-meta {
      display: flex;
      gap: 20px;
      margin-top: 8px;
      font-size: 13px;
      color: #666;

      .meta-item {
        display: inline-flex;
        align-items: center;
        gap: 5px;
      }
    }
  }

  .detail-tabs {
    :deep(.el-tabs__header) {
      margin: 0;
    }

    :deep(.el-tabs__item) {
      font-size: 14px;
      padding: 0 20px;
      height: 40px;
      line-height: 40px;
    }

    :deep(.el-tabs__content) {
      padding: 15px;
    }

    .member-management-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 10px 15px;
      margin-bottom: 10px;
      background: #f8fafc;
      border-radius: 8px;
      padding: 12px 15px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 12px;

        .search-input {
          :deep(.el-input__wrapper) {
            border-radius: 20px;
            padding-left: 12px;
          }
        }

        .refresh-btn {
          border-radius: 20px;
          padding: 8px 12px;
        }
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 12px;

        .add-member-btn {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 8px 16px;
          border-radius: 20px;
          font-weight: 500;
          transition: all 0.3s;
          box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);

          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
          }

          .arrow-icon {
            margin-left: 4px;
            font-size: 12px;
          }
        }

        .el-dropdown {
          .el-button {
            border-radius: 20px;
            padding: 8px 16px;
          }
        }
      }
    }
  }

  .detail-content {
    padding: 10px;

    .family-descriptions {
      margin-bottom: 20px;

      :deep(.desc-label) {
        width: 120px;

        .el-icon {
          margin-right: 5px;
        }
      }
    }

    .quick-stats {
      display: flex;
      gap: 20px;
      margin-top: 25px;

      .stat-card {
        flex: 1;
        background: #f9f9f9;
        border-radius: 8px;
        padding: 15px;
        display: flex;
        align-items: center;
        gap: 15px;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          background: rgba(64, 158, 255, 0.1);
          display: flex;
          align-items: center;
          justify-content: center;

          .el-icon {
            font-size: 24px;
          }
        }

        .stat-content {
          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
          }

          .stat-label {
            font-size: 13px;
            color: #666;
          }
        }
      }
    }
  }

  .member-table, .tag-table {
    :deep(.el-table__header-wrapper .cell) {
      display: flex;
      align-items: center;
      gap: 6px;
    }
  }
}

:deep(.el-tabs__item.is-active) {
  color: #1F63FF;
  font-weight: bold;
}

/* 成员编辑对话框样式 */
.member-edit-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  }

  :deep(.el-dialog__header) {
    padding: 20px;
    margin-right: 0;
    background: linear-gradient(to right, #f6f7f9, #ffffff);
    border-bottom: 1px solid #f0f0f0;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  :deep(.el-dialog__body) {
    padding: 20px;

    .el-form-item__label {
      font-weight: 500;
      color: #555;
      margin-bottom: 8px;
    }

    .el-input, .el-select, .el-textarea {
      .el-input__wrapper, .el-textarea__inner {
        border-radius: 8px;
        padding: 10px 15px;
        transition: all 0.3s;

        &:hover {
          border-color: #c0c4cc;
        }

        &:focus {
          border-color: #1F63FF;
          box-shadow: 0 0 0 2px rgba(31, 99, 255, 0.1);
        }
      }
    }
  }

  :deep(.el-dialog__footer) {
    padding: 15px 20px;
    border-top: 1px solid #f0f0f0;
    text-align: right;

    .el-button {
      padding: 10px 20px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s;

      &--default {
        &:hover {
          color: #1F63FF;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
      }

      &--primary {
        background-color: #1F63FF;
        border-color: #1F63FF;

        &:hover {
          background-color: #3a7afe;
          box-shadow: 0 4px 12px rgba(31, 99, 255, 0.3);
        }
      }
    }
  }
}
</style>
